//
//  QrCode.m
//  gdemm
//
//  Created by 乔明超 on 16/5/9.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "QrCode.h"

@implementation QrCode
-(instancetype)initWithSupperView:(UIView *)scanView
{
    self = [super init];
    if (self) {
        self.scanView = scanView;
        self.captureSession = nil;
        self.addFlag = YES;
        self.dir = 5;
    }
    
    return self;
}

- (BOOL)startReading:(setMsgHandler)setmsg
{
    self.callback = setmsg;
    NSError *error;
    //1.初始化捕捉设备（AVCaptureDevice），类型为AVMediaTypeVideo
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //2.用captureDevice创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    //3.创建媒体数据输出流
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    //4.实例化捕捉会话
    self.captureSession = [[AVCaptureSession alloc] init];
    //4.1.将输入流添加到会话
    [self.captureSession addInput:input];
    //4.2.将媒体输出流添加到会话中
    [self.captureSession addOutput:captureMetadataOutput];
    //5.创建串行队列
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    //5.1.设置代理
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    //5.2.设置输出媒体数据类型为QRCode
    [captureMetadataOutput setMetadataObjectTypes:@[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code]];
    //6.实例化预览图层
    self.videoPreviewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
    //7.设置预览图层填充方式
    [self.videoPreviewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    //8.设置图层的frame
    [self.videoPreviewLayer setFrame:self.scanView.layer.bounds];
    
    //9.将图层添加到预览view的图层上
    [self.scanView.layer addSublayer:self.videoPreviewLayer];
    
    //10.设置扫描范围
    captureMetadataOutput.rectOfInterest = CGRectMake(0.2f, 0.2f, 0.6f, 0.6f);
    
    //10.1.扫描框
    self.boxView = [[UIView alloc] initWithFrame:CGRectMake(self.scanView.bounds.size.width * 0.2f, self.scanView.bounds.size.height * 0.2f, self.scanView.bounds.size.width - self.scanView.bounds.size.width * 0.4f, self.scanView.bounds.size.height - self.scanView.bounds.size.height * 0.4f)];
    self.boxView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.1];
    self.boxView.layer.borderColor = [UIColor whiteColor].CGColor;
    self.boxView.layer.borderWidth = 1.0f;
    
    [self.scanView addSubview:self.boxView];
    
    //10.2.扫描线
    self.scanLayer = [[CALayer alloc] init];
    self.scanLayer.frame = CGRectMake(5, 0, self.boxView.bounds.size.width - 10, 1);
    self.scanLayer.backgroundColor = [UIColor greenColor].CGColor;
    
    [self.boxView.layer addSublayer:self.scanLayer];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.05f target:self selector:@selector(moveScanLayer:) userInfo:nil repeats:YES];
    //10.开始扫描
    [self.captureSession startRunning];
    
    return YES;
}

-(void)stopReading{
    [self.timer invalidate];
    [self.captureSession stopRunning];
    self.captureSession = nil;
    [self.scanLayer removeFromSuperlayer];
    [self.videoPreviewLayer removeFromSuperlayer];
}

//这个函数由新线程调用（识别完成之后）
#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    //判断是否有数据
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        //[_lblStatus performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
        //NSLog(@"扫描结果%@", [metadataObj stringValue]);
        [self performSelectorOnMainThread:@selector(transMsgToPreView:) withObject:[metadataObj stringValue] waitUntilDone:NO];
        
        [self performSelectorOnMainThread:@selector(stopReading) withObject:nil waitUntilDone:NO];
    }
}

-(void)transMsgToPreView:(NSString *)msg
{
    self.callback(msg);
}

- (void)moveScanLayer:(NSTimer *)timer
{
    CGRect frame = self.scanLayer.frame;
    if (frame.origin.y >= self.boxView.frame.size.height) {
        self.dir = -5;
    } else if (frame.origin.y <= 0) {
        self.dir = 5;
    }
    
    frame.origin.y += self.dir;
    self.scanLayer.frame = frame;
}

@end
